//
//  ViewController.swift
//  HTestLocalNotification
//
//  Created by 赵泓博 on 2025/4/25.
//

import UIKit

class ViewController: UIViewController {

    private let button: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("发送本地通知", for: .normal)
        button.backgroundColor = .red
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        button.addTarget(self, action: #selector(scheduleNotification(_ :)), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(button)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.topAnchor, constant: 200),
            button.widthAnchor.constraint(equalToConstant: 150),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    @objc func scheduleNotification(_ sender:UIButton) {
        //创建通知内容
        let content = UNMutableNotificationContent()
        content.title = "提醒"
        content.body = "您有新订单通知"
        content.sound = .default
        content.badge = 1

        //设置触发条件（例如，5秒后触发）
//        let trigger = UNTimeIntervalNotificationTrigger(
//            timeInterval: 0,
//            repeats: false
//        )
        //创建通知请求
        let request = UNNotificationRequest(
            identifier: "localNotification\(Date().timeIntervalSince1970)",
            content: content,
            trigger: nil
        )
        //添加通知请求到通知中心
        UNUserNotificationCenter.current().add(request){ error in
            if let error = error {
                print(
                    "Error scheduling notification: \(error.localizedDescription)"
                )
            } else {
                print("Notification scheduled successfully.")
            }
        }
    }

}

